<template>
  <div class="view-grid">
    <!-- 操作按钮区 -->
    <div class="grid-header">
      <div class="title">
        <h3>{{ table.cnName }}</h3>
      </div>
      <div class="btn-group">
        <el-button v-for="(btn, bIndex) in buttons" :key="bIndex" :plain="btn.plain" :type="btn.type"
          :disabled="btn.hasOwnProperty('disabled') && !!btn.disabled"
          v-show="!(typeof btn.hidden == 'boolean' && btn.hidden)" @click="onClick(btn.onClick)">
          <i :class="btn.icon"></i>{{ btn.name }}
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="grid-search">
      <mes-form ref="searchForm" :editor="false" :formRules="searchFormOptions" :formFields="searchFormFields"
        :label-width="100" @keyup.enter="search" :load-key="false"></mes-form>
      <div v-show="searchBoxShow" class="search-box">
        <mes-form ref="searchFormExt" :editor="false" :formRules="searchFormOptions" :formFields="searchFormFields"
          :label-width="100" @keyup.enter="search" :load-key="false"></mes-form>
      </div>
    </div>

    <!-- 表格区域 - 使用el-table-v2代替普通表格 -->
    <div class="grid-container">
      <el-table-v2 :columns="columns" :data="tableData" :row-height="48" :header-height="40" :width="tableWidth"
        :height="tableHeight" :row-key="rowKey" @row-click="rowOnClick" />
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted, onActivated } from 'vue';
import MesForm from '@/components/basic/MesForm.vue';
import ElTableV2 from 'element-plus/es/components/table-v2/src/table-v2';
import props from './props.js';
import methods from './methods.js';

const _const = {
  SEARCH: 'search'
};

export default defineComponent({
  components: {
    'mes-form': MesForm,
    'el-table-v2': ElTableV2
  },
  props: {
    ...props
  },
  setup(props) {
    // 组件相关的响应式数据
    const searchBoxShow = ref(false);
    const fiexdSearchForm = ref(false);
    const tableMaxHeight = ref(0);
    const keyValueType = reactive({});
    const maxBtnLength = ref(10);
    const tableData = ref([]);
    const loading = ref(false);

    // 按钮相关
    const buttons = ref([
      {
        name: '查询',
        icon: 'el-icon-search',
        type: 'primary',
        value: 'Search',
        onClick: () => {
          methods.search.apply({ ...methods, $refs: { table: { load: () => loadData(true) } } });
        }
      }
    ]);

    // 计算表格宽度和高度
    const tableWidth = computed(() => {
      return '100%';
    });

    const tableHeight = computed(() => {
      return props.height || 'calc(100vh - 240px)';
    });

    // 加载数据方法
    const loadData = async (resetPage = false) => {
      loading.value = true;
      try {
        const queryParams = methods.getSearchParameters.apply({
          searchFormFields: props.searchFormFields,
          searchFormOptions: props.searchFormOptions,
          emptyValue: methods.emptyValue,
          getSearchItem: methods.getSearchItem,
          searchBoxShow,
          fiexdSearchForm
        });

        // 调用loadBefore钩子
        const beforeResult = methods.searchBefore.apply({}, [queryParams]);
        if (beforeResult === false) {
          return;
        }

        // 这里应该调用API获取数据
        // 示例：const response = await api.getList(queryParams);
        // tableData.value = response.data;

        // 调用loadAfter钩子
        methods.searchAfter.apply({}, [tableData.value, null]);
      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        loading.value = false;
      }
    };

    const initDicKeys = () => {
      if (methods.initDicKeys) {
        methods.initDicKeys.apply({
          dicKeys: [], // 提供空数组作为dicKeys
          searchFormOptions: props.searchFormOptions || [],
          searchFormFields: props.searchFormFields || {},
          columns: props.columns || [],
          singleSearch: {}, // 提供singleSearch对象
          numberFields: [], // 提供numberFields数组
          uploadfiled: [], // 提供uploadfiled数组
          remoteKeys: [], // 提供remoteKeys数组
          // 添加缺失的initFormOptions函数
          initFormOptions: (formOptions, keys, formFields, isEdit) => {
            // 基本实现，确保不会报错
            if (!formOptions || !Array.isArray(formOptions)) return;
            
            formOptions.forEach((item) => {
              if (!item || !Array.isArray(item)) return;
              item.forEach((field) => {
                // 处理表单字段配置
                if (field && field.type) {
                  // 存储字典编号
                  if (field.dicNo) {
                    keys.push(field.dicNo);
                  }
                  
                  // 初始化字段默认值
                  if (formFields && field.name !== undefined) {
                    if (formFields[field.name] === undefined) {
                      formFields[field.name] = '';
                    }
                  }
                }
              });
            });
          },
          // 添加缺失的initColumns函数
          initColumns: (columns, dicKeys, keys) => {
            // 基本实现，确保不会报错
            if (!columns || !Array.isArray(columns)) return;
            
            columns.forEach((column) => {
              if (!column) return;
              
              // 存储字典编号
              if (column.dicNo) {
                keys.push(column.dicNo);
                
                // 创建字典配置对象
                if (dicKeys && Array.isArray(dicKeys)) {
                  dicKeys.push({
                    dicNo: column.dicNo,
                    data: [],
                    orginData: []
                  });
                }
              }
            });
          }
        });
      }
    }

    // 初始化按钮
    const initBoxButtons = () => {
      if (methods.initBoxButtons) {
        methods.initBoxButtons.apply({
          buttons, 
          $route: { path: '' },
          permission: {
            getButtons: () => []
          },
          extend: props.extend || {},
          table: props.table || {},
          extendBtn: methods.extendBtn
        });
      }
    };

    // 获取按钮
    const getButtons = () => {
      if (methods.getButtons) {
        methods.getButtons.apply({
          buttons: buttons.value, // 使用buttons.value
          searchFormOptions: props.searchFormOptions,
          fiexdSearchForm,
          searchBoxShow
        });
      }
    };

    // 点击按钮事件
    const onClick = (click) => {
      click.apply({ ...methods, search: () => loadData(true) });
    };

    // 行点击事件
    const rowOnClick = (row) => {
      if (props.extend && props.extend.methods && props.extend.methods.rowOnClick) {
        props.extend.methods.rowOnClick(row);
      }
    };

    // 初始化
    onMounted(() => {
      initBoxButtons();
      initDicKeys();
      getButtons();
      if (props.load) {
        loadData();
      }
    });

    onActivated(() => {
      if (props.load) {
        loadData();
      }
    });

    return {
      const: _const,
      searchBoxShow,
      fiexdSearchForm,
      buttons,
      tableMaxHeight,
      keyValueType,
      maxBtnLength,
      tableData,
      loading,
      tableWidth,
      tableHeight,
      onClick,
      rowOnClick,
      search: () => loadData(true),
      resetSearch: methods.resetSearch.bind({
        resetSearchForm: methods.resetSearchForm.bind({
          resetForm: methods.resetForm.bind({}),
          searchFormOptions: props.searchFormOptions,
          searchFormFields: props.searchFormFields
        })
      })
    };
  }
});
</script>

<style lang="less" scoped>
@import './VirtualGrid.less';
</style>